package com.drawing.dao;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.drawing.common.SupplierLazy;
import com.drawing.common.util.JdbcTemplateUtils;
import com.drawing.pojo.ImageInfo;
import com.drawing.pojo.param.ImageParam;
import com.google.common.collect.Lists;

/**
 * @author zhaozhenhang <zhaozhenhang@kuaishou.com>
 * Created on 2023-10-10
 */
@Component
public class ImageDAO {

    private static final SupplierLazy<JdbcTemplate> JDBC_TEMPLATE = SupplierLazy.lazy(JdbcTemplateUtils::init);


    private JdbcTemplate writeJdbcTemplate() {
        return JDBC_TEMPLATE.get();
    }

    public void insert(String fileUrl, String fileName) throws IllegalAccessException {
        String sql = "insert into image_info(file_name, file_url, type, priority, create_time, data) " +
                "values (?, ?, ?, ?, ?, ?)";
        Object[] values = new Object[] {fileName, fileUrl, 0, 1, System.currentTimeMillis(), "{\"test\": \"111\"}"};
        int ret = writeJdbcTemplate().update(sql, values);
        if (ret <= 0) {
            throw new IllegalAccessException("mysql插入错误，执行sql: " + sql);
        }
    }

    public List<ImageInfo> query(ImageParam param) {
        String sql = "select * from image_info where 1 = 1 ";
        StringBuilder builder = new StringBuilder(sql);
        List<String> params = Lists.newArrayList();
        if (isNotBlank(param.getFileName())) {
            builder.append(" and file_name = ?");
            params.add(param.getFileName());
        }
        if (isNotBlank(param.getType())) {
            builder.append(" and type = ?");
            params.add(param.getType());
        }
        return writeJdbcTemplate().queryForList(builder.toString(), params.toArray())
                .stream()
                .map(map -> {
                    ImageInfo picture = new ImageInfo();
                    picture.setId((Long) map.get("id"));
                    picture.setFileName((String) map.get("file_name"));
                    picture.setFileUrl((String) map.get("file_url"));
                    picture.setType((String) map.get("type"));
                    picture.setPriority((Integer) map.get("priority"));
                    picture.setCreat_time((Long) map.get("create_time"));
                    picture.setData((String) map.get("data"));
                    return picture;
                }).collect(Collectors.toList());
    }
}
